package com.HPUCA.QQchat.service;

import com.HPUCA.QQchat.data.UserDate;
import com.HPUCA.QQchat.entity.Account;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class ChatServer {
    public static void main(String[] args) throws Exception {
        ServerSocket ss = new ServerSocket(UserDate.POINT);
        System.out.println("等待用户连接...");
        while (true){
            Socket s = ss.accept();
            OutputStream out = s.getOutputStream();
            InputStream in = s.getInputStream();

            OutputStreamWriter osw = new OutputStreamWriter(out);
            PrintWriter pw = new PrintWriter(osw, true);
            InputStreamReader isr = new InputStreamReader(in);
            BufferedReader br = new BufferedReader(isr);

            String name = br.readLine();
            boolean flag = false;
            for (Account a : UserDate.USERS) {
                if (a.getName().equals(name)) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                pw.println("用户名重复,请换个试试!");
            } else {
                pw.println("success");
                Account a = new Account();
                a.setName(name);
                a.setRead(br);
                a.setWrite(pw);
                UserDate.USERS.add(a);
                for (Account u : UserDate.USERS) {
                    u.getWrite().println("【" + name + "】加入了聊天室,当前在线人数" + UserDate.USERS.size());
                }
                System.out.println("【" + name + "】加入了聊天室,当前在线人数" + UserDate.USERS.size());
                Thread th = new Thread(new SendMessage(a));
                th.start();
            }
        }
    }
}
